package com.jz.community.moduleshopping.confirmOrder.model;

import android.annotation.SuppressLint;
import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.jz.community.basecomm.bean.baseGoods.GoodInfo;
import com.jz.community.basecomm.bean.baseGoods.ShopInfo;
import com.jz.community.basecomm.bean.baseGoods.ShopListInfo;
import com.jz.community.basecomm.constant.AppConstants;
import com.jz.community.basecomm.net.retrofit.ApiException;
import com.jz.community.basecomm.net.retrofit.ApiUtils;
import com.jz.community.basecomm.net.retrofit.HttpRxObservable;
import com.jz.community.basecomm.net.retrofit.JsonRequestBodyConverter;
import com.jz.community.basecomm.net.retrofit.RxLoadingWrapper;
import com.jz.community.basecomm.net.rxandroid.OnLoadListener;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.LoggerUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.moduleshopping.confirmOrder.bean.BaseOrderCouponInfo;
import com.jz.community.moduleshopping.confirmOrder.bean.OrderCouponInfo;
import com.jz.community.moduleshopping.confirmOrder.bean.UpdateOrderCouponInfo;
import com.jz.community.moduleshopping.confirmOrder.bean.OrderPayResultBean;
import com.jz.community.moduleshopping.confirmOrder.bean.OrderPostageInfo;
import com.jz.community.moduleshopping.confirmOrder.bean.SubmitOrderBean;
import com.jz.community.moduleshopping.confirmOrder.bean.SubmitOrderResultBean;
import com.jz.community.moduleshopping.confirmOrder.bean.UpdateCouponInfo;
import com.jz.community.moduleshopping.confirmOrder.net.ConfirmOrderApi;
import com.jz.community.moduleshopping.goodsDetail.bean.GoodsCouponInfo;
import com.trello.rxlifecycle2.components.support.RxFragmentActivity;

import java.util.ArrayList;
import java.util.List;

import cn.shequren.communityPeople.pay.constants.PayConstants;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * Created by Tony.Fan on 2018/4/4 11:38
 */
public class ConfirmOrderModelImpl implements ConfirmOrderModel {

    private Context mContext;

    public ConfirmOrderModelImpl(Context context) {
        mContext = context;
    }


    @SuppressLint("CheckResult")
    @Override
    public void submitOrder(SubmitOrderBean orderSubmit, OnLoadListener<SubmitOrderResultBean> onLoadListener) {
        Observable<SubmitOrderResultBean> infoObservable = HttpRxObservable.getObservable((RxFragmentActivity) mContext, ApiUtils.getApi(mContext, ConfirmOrderApi.class)
                .submitOrder(new JsonRequestBodyConverter<SubmitOrderBean>().convert(orderSubmit)));
        new RxLoadingWrapper<SubmitOrderResultBean>(mContext)
                .execute(infoObservable)
                .subscribe(new Consumer<SubmitOrderResultBean>() {
                    @Override
                    public void accept(SubmitOrderResultBean submitOrderResultBean) throws Exception {
                        if (submitOrderResultBean == null) {
                            return;
                        }
                        onLoadListener.onSuccess(submitOrderResultBean);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        onLoadListener.onFail(ApiException.handleException(throwable).message, ApiException.handleException(throwable).code);
                    }
                });
    }

    @Override
    public void orderPostage(SubmitOrderBean orderSubmit, OnLoadListener<OrderPostageInfo> onLoadListener) {
        Observable<OrderPostageInfo> infoObservable = HttpRxObservable.getObservable((RxFragmentActivity) mContext, ApiUtils.getApi(mContext, ConfirmOrderApi.class)
                .orderPostage(new JsonRequestBodyConverter<SubmitOrderBean>().convert(orderSubmit)));
        new RxLoadingWrapper<OrderPostageInfo>(mContext, false)
                .execute(infoObservable)
                .subscribe(new Consumer<OrderPostageInfo>() {
                    @Override
                    public void accept(OrderPostageInfo submitOrderResultBean) throws Exception {
                        if (submitOrderResultBean == null) {
                            return;
                        }
                        onLoadListener.onSuccess(submitOrderResultBean);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        onLoadListener.onFail(ApiException.handleException(throwable).message, ApiException.handleException(throwable).code);
                    }
                });
    }


    @SuppressLint("CheckResult")
    @Override
    public void orderPay(String id, String payType, OnLoadListener<OrderPayResultBean> onLoadListener) {
        Observable<OrderPayResultBean> observable = HttpRxObservable.getObservable((RxFragmentActivity) mContext, ApiUtils.getApi(mContext, ConfirmOrderApi.class)
                .orderPay(id, payType));
        new RxLoadingWrapper<OrderPayResultBean>(mContext, true)
                .execute(observable)
                .subscribe(resultBean -> {
                    if (resultBean == null) {
                        return;
                    }
                    onLoadListener.onSuccess(resultBean);
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        onLoadListener.onFail(throwable.toString(), ApiException.handleException(throwable).code);
                        WpToast.l(mContext, ApiException.handleException(throwable).message);
                    }
                });
    }

    @SuppressLint("CheckResult")
    @Override
    public void requestOrderPlatformAndShopCouponInfo(List<UpdateOrderCouponInfo> shopVoList, OnLoadListener<OrderCouponInfo> onLoadListener) {
        Observable<OrderCouponInfo> infoObservable = HttpRxObservable.getObservable((RxFragmentActivity) mContext, ApiUtils.getApi(mContext, ConfirmOrderApi.class)
                .getOrderPlatformAndShopCouponInfo(new JsonRequestBodyConverter<List<UpdateOrderCouponInfo>>().convert(shopVoList), AppConstants.APPID));
        new RxLoadingWrapper<OrderCouponInfo>(mContext, false)
                .execute(infoObservable)
                .subscribe(new Consumer<OrderCouponInfo>() {
                    @Override
                    public void accept(OrderCouponInfo orderCouponInfo) throws Exception {
                        if (orderCouponInfo == null) {
                            return;
                        }
                        onLoadListener.onSuccess(orderCouponInfo);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        onLoadListener.onFail(throwable.toString(), ApiException.handleException(throwable).code);
                    }
                });
    }

    @Override
    public void requestOrderPlatformCouponInfo(List<UpdateOrderCouponInfo> shopVoList, OnLoadListener<List<BaseOrderCouponInfo>> onLoadListener) {
        Observable<List<BaseOrderCouponInfo>> infoObservable = HttpRxObservable.getObservable((RxFragmentActivity) mContext, ApiUtils.getApi(mContext, ConfirmOrderApi.class)
                .getOrderPlatformCouponInfo(new JsonRequestBodyConverter<List<UpdateOrderCouponInfo>>().convert(shopVoList), AppConstants.APPID));
        new RxLoadingWrapper<List<BaseOrderCouponInfo>>(mContext, false)
                .execute(infoObservable)
                .subscribe(new Consumer<List<BaseOrderCouponInfo>>() {
                    @Override
                    public void accept(List<BaseOrderCouponInfo> orderCouponInfo) throws Exception {
                        if (orderCouponInfo == null) {
                            return;
                        }
                        onLoadListener.onSuccess(orderCouponInfo);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        onLoadListener.onFail(throwable.toString(), ApiException.handleException(throwable).code);
                        onLoadListener.onSuccess(new ArrayList<>());
                    }
                });
    }

    @SuppressLint("CheckResult")
    @Override
    public void requestUpdateOrderCouponInfo(UpdateCouponInfo updateCouponInfo, OnLoadListener<GoodsCouponInfo> onLoadListener) {
        Observable<GoodsCouponInfo> infoObservable = HttpRxObservable.getObservable((RxFragmentActivity) mContext, ApiUtils.getApi(mContext, ConfirmOrderApi.class)
                .getUpdateOrderCouponInfo(new JsonRequestBodyConverter<UpdateCouponInfo>().convert(updateCouponInfo)));
        new RxLoadingWrapper<GoodsCouponInfo>(mContext, false)
                .execute(infoObservable)
                .subscribe(new Consumer<GoodsCouponInfo>() {
                    @Override
                    public void accept(GoodsCouponInfo orderCouponInfo) throws Exception {
                        if (orderCouponInfo == null) {
                            return;
                        }
                        onLoadListener.onSuccess(orderCouponInfo);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        onLoadListener.onFail(throwable.toString(), ApiException.handleException(throwable).code);
                    }
                });
    }

    /**
     * 创建订单封装
     *
     * @param shopInfo
     * @param consigneeAddress
     * @param consigneeName
     * @param consigneePhone
     * @param couponId
     */
    @Override
    public SubmitOrderBean createConfirmOrderData(ShopInfo shopInfo, String addressId, String consigneeAddress, String consigneeName, String consigneePhone, String couponId, String cityCode, double sendPrice, String mentionId, String mentionName, String mentionPhone) {
        return submitOrderBean(shopInfo, addressId, consigneeAddress, consigneeName, consigneePhone, couponId, cityCode, sendPrice, mentionId, mentionName, mentionPhone);
    }


    /**
     * 提交订单
     *
     * @param shopInfo
     * @param consigneeAddress
     * @param consigneeName
     * @param consigneePhone
     * @param couponId
     * @param cityCode
     * @param sendPrice
     * @param mentionId
     * @param mentionName
     * @param mentionPhone
     * @return
     */
    private SubmitOrderBean submitOrderBean(ShopInfo shopInfo, String addressId, String consigneeAddress, String consigneeName, String consigneePhone, String couponId, String cityCode, double sendPrice, String mentionId, String mentionName, String mentionPhone) {
        SubmitOrderBean submitOrderBean = new SubmitOrderBean();
        submitOrderBean.setPlatformId(PayConstants.PLATFORMID);
        submitOrderBean.setCartIds(shopInfo.getCartIds());
        submitOrderBean.setOrderType("OnLinePay");
        submitOrderBean.setBuySource("SQR_USER");
        submitOrderBean.setAddressId(addressId);
        submitOrderBean.setAddress(consigneeAddress);
        submitOrderBean.setAddressName(consigneeName);
        submitOrderBean.setAddressPhone(consigneePhone);
        submitOrderBean.setCityCode(cityCode);
        submitOrderBean.setMentionId(mentionId);
        submitOrderBean.setCouponId(couponId);
        submitOrderBean.setMentionName(mentionName);
        submitOrderBean.setMentionPhone(mentionPhone);
        submitOrderBean.setSendType(shopInfo.getSendType());
        List<SubmitOrderBean.VoListBean> voList = new ArrayList<>();
        for (ShopListInfo itemShop : shopInfo.getShopList()) {
            SubmitOrderBean.VoListBean voListBean = new SubmitOrderBean.VoListBean();
            voListBean.setCouponId(itemShop.getCouponId());
            voListBean.setShopId(itemShop.getShopId());
            voListBean.setSendPrice(ConverterUtils.toString(sendPrice));
            voListBean.setUserInfo(itemShop.getUserRemark());
            voListBean.setOrderSource(PayConstants.ORDER_SOURCE);
            List<SubmitOrderBean.VoListBean.OrderItemVOListBean> list = new ArrayList<>();
            for (GoodInfo itemGoodsInfo : itemShop.getGoodsList()) {
                SubmitOrderBean.VoListBean.OrderItemVOListBean orderItemVOListBean = new SubmitOrderBean.VoListBean.OrderItemVOListBean();
                orderItemVOListBean.setGoodsId(itemGoodsInfo.getId());
                orderItemVOListBean.setGoodsCount(itemGoodsInfo.getNums());
                orderItemVOListBean.setCategoryId(itemGoodsInfo.getCategoryId());
                orderItemVOListBean.setCode(shopInfo.getCode());
                orderItemVOListBean.setSkuId(itemGoodsInfo.getSkuId());
                list.add(orderItemVOListBean);
            }
            voListBean.setOrderItemVOList(list);
            voList.add(voListBean);
        }
        submitOrderBean.setVoList(voList);
        LoggerUtils.Log().i(JSON.toJSON(submitOrderBean));
        return submitOrderBean;
    }

    /**
     * 平台、商家优惠券参数封装
     *
     * @param shopInfo
     * @return
     */
    @Override
    public List<UpdateOrderCouponInfo> orderPlatformAndShopCouponParam(ShopInfo shopInfo) {
        List<UpdateOrderCouponInfo> shopVoList = new ArrayList<>();
        for (ShopListInfo itemShopList : shopInfo.getShopList()) {
            UpdateOrderCouponInfo updateOrderCouponInfo = new UpdateOrderCouponInfo();
            updateOrderCouponInfo.setShopId(itemShopList.getShopId());
            List<UpdateOrderCouponInfo.GoodsVoListBean> goodsVoList = new ArrayList<>();
            for (GoodInfo itemGoodsInfo : itemShopList.getGoodsList()) {
                UpdateOrderCouponInfo.GoodsVoListBean goodsVoListBean = new UpdateOrderCouponInfo.GoodsVoListBean();
                goodsVoListBean.setGoodsCategoriesId(itemGoodsInfo.getCategoryId());
                goodsVoListBean.setGoodsId(itemGoodsInfo.getId());
                goodsVoListBean.setGoodsPrice(Preconditions.isNullOrEmpty(itemGoodsInfo.getDisCountPrice()) ? itemGoodsInfo.getPrice() : itemGoodsInfo.getDisCountPrice());
                goodsVoListBean.setSkuId(itemGoodsInfo.getSkuId());
                goodsVoListBean.setSum(itemGoodsInfo.getNums());
                goodsVoList.add(goodsVoListBean);
            }
            updateOrderCouponInfo.setGoodsVoList(goodsVoList);
            shopVoList.add(updateOrderCouponInfo);
        }
        LoggerUtils.Log().i("优惠券" + JSON.toJSON(shopVoList));
        return shopVoList;
    }

    /**
     * 平台优惠券参数封装
     *
     * @param shopInfo
     * @return
     */
    @Override
    public List<UpdateOrderCouponInfo> orderPlatformCouponParam(ShopInfo shopInfo) {
        List<UpdateOrderCouponInfo> shopVoList = new ArrayList<>();
        for (ShopListInfo itemShopList : shopInfo.getShopList()) {
            UpdateOrderCouponInfo updateOrderCouponInfo = new UpdateOrderCouponInfo();
            updateOrderCouponInfo.setShopId(itemShopList.getShopId());
            updateOrderCouponInfo.setCouponSubMoney(Preconditions.isNullOrEmpty(itemShopList.getCouponSubMoney()) ? "0" : itemShopList.getCouponSubMoney());
            updateOrderCouponInfo.setCouponId(itemShopList.getCouponId());
            List<UpdateOrderCouponInfo.GoodsVoListBean> goodsVoList = new ArrayList<>();
            for (GoodInfo itemGoodsInfo : itemShopList.getGoodsList()) {
                UpdateOrderCouponInfo.GoodsVoListBean goodsVoListBean = new UpdateOrderCouponInfo.GoodsVoListBean();
                goodsVoListBean.setGoodsCategoriesId(itemGoodsInfo.getCategoryId());
                goodsVoListBean.setGoodsId(itemGoodsInfo.getId());
                goodsVoListBean.setGoodsPrice(Preconditions.isNullOrEmpty(itemGoodsInfo.getDisCountPrice()) ? itemGoodsInfo.getPrice() : itemGoodsInfo.getDisCountPrice());
                goodsVoListBean.setSkuId(itemGoodsInfo.getSkuId());
                goodsVoListBean.setSum(itemGoodsInfo.getNums());
                goodsVoList.add(goodsVoListBean);
            }
            updateOrderCouponInfo.setGoodsVoList(goodsVoList);
            shopVoList.add(updateOrderCouponInfo);
            LoggerUtils.Log().i("优惠券" + JSON.toJSON(shopVoList));
        }
        return shopVoList;
    }

}
